<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="nav-bar" :style="{ paddingTop: statusBarHeight*1.6 + 'px' }">
			<view class="nav-content">
				<view class="left-icon" @click="openMenu">
					<uni-icons type="closeempty" size="24" color="#fff"></uni-icons>
				</view>
				<!-- <view class="right-icon" @click="closeWindow">
					<uni-icons type="bars" type="closeempty" size="24" color="#fff"></uni-icons>
				</view> -->
			</view>
		</view>

		<!-- 骨架屏 -->
		<view class="skeleton-container" v-if="loading">
			<skeleton :show-image="true" image-height="500rpx" :show-title="true" title-width="80%" title-height="40rpx"
				:show-avatar="true" avatar-size="80rpx" username-width="40%" :rows="5" row-width="100%"
				row-height="30rpx"></skeleton>
		</view>

		<!-- 主要内容区 -->
		<scroll-view v-else class="content" scroll-y>
			<!-- 主图 -->
			<image class="main-image" :src="detail.image" mode="widthFix"></image>

			<!-- 内容区域 -->
			<view class="content-box">
				<!-- 标题区域 -->
				<view class="title-section">
					<text class="title">{{detail.content}}</text>
					<text class="date">{{detail.createdAt}}</text>
				</view>

				<!-- 用户信息 -->
				<view class="user-info">
					<view class="user-left">
						<image class="avatar" :src="detail.avatar"></image>
						<view class="user-detail">
							<text class="username">{{detail.userName}}</text>
						</view>
					</view>
					<!-- 打赏按钮 -->
					<view class="reward-btn" @click="handleReward" v-if="isDetele==0">
						<uni-icons type="gift" size="20" color="#ff2442"></uni-icons>
						<text>施舍</text>
					</view>
				</view>

				<!-- 评论区域 -->
				<view class="comments-section">
					<view class="comment-count">共{{detail.comments.length}}条评论</view>
					<view class="comment-item" v-for="(comment, index) in detail.comments" :key="index">
						<image class="comment-avatar" :src="comment.avatar"></image>
						<view class="comment-content">
							<text class="comment-username">{{comment.userName}}</text>
							<text class="comment-text"
								@click="handleCommentClick(comment.id)">{{comment.content}}</text>
							<text class="comment-date">{{comment.date}}</text>
							<!-- 添加二级评论 -->
							<view class="reply-list" v-if="comment.replies && comment.replies.length">
								<view class="reply-item" v-for="(reply, replyIndex) in comment.replies"
									:key="replyIndex">
									<image class="reply-avatar" :src="reply.avatar"></image>
									<view class="reply-content">
										<view class="reply-user">
											<text class="reply-username">{{reply.userName}}</text>
											<text class="reply-to">回复</text>
											<text class="reply-target">{{reply.replyTo}}</text>
										</view>
										<text class="reply-text"
											@click="handleCommentClick(reply.id)">{{reply.content}}</text>
										<text class="reply-date">{{reply.date}}</text>
									</view>
								</view>
							</view>
						</view>
						<view class="comment-like">
						</view>
					</view>
				</view>
			</view>
			<!-- 添加底部结束标记 -->
			<view class="end-mark">
				<text>- THE END -</text>
			</view>
		</scroll-view>

		<!-- 底部操作栏 -->
		<view class="bottom-bar">
			<view class="input-box">
				<uni-icons type="compose" size="20" color="#666"></uni-icons>
				<input type="text" v-model="commentText" placeholder="说点什么..." :focus="inputFocus"
					@blur="handleInputBlur" @confirm="handleSendComment" />
			</view>
			<view class="action-box">
				<view class="action-item">
					<uni-icons type="chat" size="24" color="#666"></uni-icons>
					<text>{{detail.comments.length}}</text>
				</view>
				<view class="action-item send-btn" @click="handleSendComment">
					<uni-icons type="paperplane-filled" size="16" color="#fff"></uni-icons>
					<text>发送</text>
				</view>
			</view>
		</view>

		<!-- 打赏礼物弹窗 -->
		<uni-popup ref="giftPopup" type="bottom">
			<view class="gift-popup">
				<view class="gift-header">
					<text class="gift-title">赠送礼物</text>
					<view class="close-btn" @click="closeGiftPopup">
						<uni-icons type="closeempty" size="24" color="#666"></uni-icons>
					</view>
				</view>
				<view class="gift-grid">
					<view class="gift-item" :class="{ active: selectedGift && selectedGift.id === gift.id }"
						v-for="(gift, index) in giftList" :key="index" @click="selectGift(gift)">
						<image class="gift-icon" :src="gift.icon" mode="aspectFit"></image>
						<text class="gift-name">{{gift.name}}</text>
						<text class="gift-price">￥{{gift.price}}</text>
					</view>
				</view>
				<view class="gift-footer">
					<button class="send-btn" @click="sendGift">赠送</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		getpostsDetail,
		getCommentsDetail,
		setCommentsDetail,
		payOrders,
		getGifts,
		postGifts,
		getSetings
	} from "@/request/API.js";
	import Skeleton from '../../compents/skeleton/skeleton.vue';

	export default {
		data() {
			return {
				statusBarHeight: 0,
				selectedGift: null,
				commentText: '',
				inputFocus: false,
				activeComment: null,
				detail: {},
				giftList: [],
				isDetele: 0,
				loading: true // 添加加载状态
			}
		},
		components: {
			Skeleton
		},
		created() {
			this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight;
		},
		onLoad(options) {
			console.log(options);
			if (options?.id != null) {
				getApp().globalData.data = {
					id: options.id
				}
			}
			this.init();
		},
		onShareAppMessage() {
			return {
				title: this.detail.content, // 分享标题
				path: '/pages/tong/tong?id=' + getApp().globalData.data.id, // 分享路径（必须是当前页面的路径）
				imageUrl: this.detail.image, // 分享图片（支持本地和网络路径）
				success: (res) => {
					console.log('分享成功', res);
				},
				fail: (err) => {
					console.log('分享失败', err);
				}
			};
		},
		methods: {
			async init() {
				this.loading = true; // 开始加载
				try {
					let code = await getSetings();
					this.isDetele = code.data.isDelete;
					console.log(this.isDetele);
					const {
						data
					} = await getpostsDetail(getApp().globalData.data.id);
					const reslut = await getCommentsDetail(data.id);
					data.comments = reslut.data;
					this.detail = data;
					let res = await getGifts();
					this.giftList = res.data;
				} catch (error) {
					console.error('加载详情失败:', error);
					uni.showToast({
						title: '加载失败，请重试',
						icon: 'none'
					});
				} finally {
					this.loading = false; // 加载完成
				}
			},
			openMenu() {
				uni.navigateTo({
					url: "/pages/index/index"
				})
			},
			closeWindow() {
				uni.navigateTo({
					url: "/pages/index/index"
				})
			},
			/* handleReward() {
				uni.showToast({
					title: '打赏功能开发中',
					icon: 'none'
				})
			}, */
			handleReward() {
				this.$refs.giftPopup.open()
			},
			closeGiftPopup() {
				this.$refs.giftPopup.close()
				this.selectedGift = null
			},
			selectGift(gift) {
				this.selectedGift = gift
			},
			sendGift() {
				let that = this;
				if (!this.selectedGift) {
					uni.showToast({
						title: '请选择礼物',
						icon: 'none'
					})
					return
				}
				uni.showModal({
					title: '确认支付',
					content: `确定要支付${this.selectedGift.price}元赠送${this.selectedGift.name}吗？`,
					success: async (res) => {
						if (res.confirm) {

							uni.getProvider({
								service: "payment",
								async success(payMent) {
									console.log(payMent);
									let {
										data
									} = await payOrders({
										goodId: that.selectedGift.id,
										userId: uni.getStorageSync("userId"),
										postId: getApp().globalData.data.id
									});
									uni.requestPayment({
										orderInfo: that.selectGift.name,
										provider: payMent.provider[0],
										nonceStr: data.nonceStr,
										package: data.packageStr,
										signType: data.signType,
										paySign: data.paySign,
										timeStamp: data.timeStamp
									})
								}
							})

							uni.showToast({
								title: '赠送成功',
								icon: 'success'
							})
							this.closeGiftPopup()
						}
					}
				})
			},
			handleCommentClick(comment) {
				this.activeComment = comment;
				this.inputFocus = true;
			},
			handleInputBlur() {
				this.inputFocus = false;
			},
			async handleSendComment() {
				let id = uni.getStorageSync("userId");
				if (!this.commentText.trim()) {
					uni.showToast({
						title: '请输入评论内容',
						icon: 'none'
					});
					return;
				}
				if (!id) {
					uni.showToast({
						title: '未登录请先登录',
						icon: 'none',
						success() {
							uni.switchTab({
								url: "/pages/profile/profile"
							})
						}
					});
					return;
				}

				console.log('回复的评论:', this.activeComment);
				console.log('评论内容:', this.commentText);
				let res = await setCommentsDetail({
					postId: this.detail.id,
					userId: id,
					parentId: this.activeComment,
					content: this.commentText
				});
				if (res.code == 200) {
					this.init()
					// 清空输入
					this.commentText = '';
					this.activeComment = null;
					this.inputFocus = false;
					uni.showToast({
						icon: "success",
						duration: 2000,
						title: res.data
					})
				}

			}
		}
	}
</script>

<style>
	.container {
		height: 100vh;
		display: flex;
		flex-direction: column;
		background-color: #f8f8f8;
	}

	.nav-bar {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 999;
	}

	.nav-content {
		height: 44px;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0 16rpx;
	}

	.left-icon,
	.right-icon {
		width: 44px;
		height: 44px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.content {
		flex: 1;
		overflow: hidden;
	}

	.main-image {
		width: 100%;
		height: auto;
		display: block;
	}

	.content-box {
		padding: 30rpx;
		background: #fff;
	}

	.title-section {
		margin-bottom: 20rpx;
	}

	.title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 10rpx;
		display: block;
	}

	.date {
		font-size: 24rpx;
		color: #999;
	}

	.user-info {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 20rpx;
		padding-bottom: 20rpx;
		border-bottom: 1px solid #eee;
	}

	.user-left {
		display: flex;
		align-items: center;
	}

	.user-detail {
		display: flex;
		flex-direction: column;
		margin-left: 20rpx;
	}

	.avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
	}

	.username {
		font-size: 28rpx;
		color: #333;
		font-weight: 500;
		margin-bottom: 6rpx;
	}

	.user-desc {
		font-size: 24rpx;
		color: #999;
	}

	.reward-btn {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 12rpx 30rpx;
		background: #fff;
		border: 1px solid #ff2442;
		background: rgba(255, 36, 66, 0.05);
		border-radius: 30rpx;
		width: fit-content;
		transition: all 0.3s;
	}

	.reward-btn:active {
		transform: scale(0.95);
		background: rgba(255, 36, 66, 0.1);
	}

	.reward-btn text {
		font-size: 26rpx;
		color: #ff2442;
		margin-left: 8rpx;
	}

	.comments-section {
		padding-top: 20rpx;
	}

	.comment-count {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 20rpx;
	}

	.comment-item {
		display: flex;
		margin-bottom: 30rpx;
	}

	.comment-avatar {
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		margin-right: 20rpx;
	}

	.comment-content {
		flex: 1;
	}

	.comment-username {
		font-size: 26rpx;
		color: #666;
		margin-bottom: 6rpx;
		display: block;
	}

	.comment-text {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 6rpx;
		display: block;
	}

	.comment-date {
		font-size: 24rpx;
		color: #999;
	}

	.comment-like {
		padding: 0 10rpx;
	}

	.bottom-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 110rpx;
		background: #fff;
		border-top: 1px solid #f0f0f0;
		display: flex;
		align-items: center;
		padding: 0 30rpx 0 20rpx;
		box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.05);
		z-index: 100;
		padding-bottom: calc(10rpx + env(safe-area-inset-bottom));
	}

	.input-box {
		flex: 2;
		display: flex;
		align-items: center;
		border-radius: 36rpx;
		background-color: #f6f7f9;
		height: 70rpx;
		padding: 0 16rpx;
		border: 1rpx solid #eaeaea;
		transition: all 0.3s;
	}

	.input-box:focus-within {
		background-color: #fff;
		border: 1rpx solid #dcdfe6;
		box-shadow: 0 0 0 2rpx rgba(255, 36, 66, 0.1);
	}

	.input-box uni-icons {
		margin-left: 10rpx;
	}

	.input-box input {
		flex: 1;
		height: 70rpx;
		margin-left: 10rpx;
		font-size: 28rpx;
		color: #333;
	}

	.action-box {
		display: flex;
		align-items: center;
	}

	.action-item {
		display: flex;
		align-items: center;
		margin-left: 30rpx;
	}

	.action-item text {
		font-size: 26rpx;
		color: #666;
		margin-left: 6rpx;
	}

	.action-item.send-btn {
		background: linear-gradient(to right, #ff6b9a, #ff4785);
		padding: 12rpx 30rpx;
		border-radius: 36rpx;
		display: flex;
		align-items: center;
		box-shadow: 0 4rpx 8rpx rgba(255, 71, 133, 0.2);
		transition: all 0.3s;
	}

	.action-item.send-btn:active {
		transform: scale(0.95);
	}

	.action-item.send-btn text {
		color: #fff;
		font-size: 28rpx;
		margin-left: 6rpx;
	}

	.reply-list {
		margin-left: 20rpx;
		margin-top: 20rpx;
		padding-left: 20rpx;
	}

	.reply-item {
		display: flex;
		margin-bottom: 20rpx;
	}

	.reply-avatar {
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		margin-right: 10rpx;
	}

	.reply-content {
		flex: 1;
	}

	.reply-user {
		display: flex;
		align-items: center;
		margin-bottom: 4rpx;
	}

	.reply-username {
		font-size: 24rpx;
		color: #666;
	}

	.reply-to {
		font-size: 24rpx;
		color: #999;
		margin: 0 6rpx;
	}

	.reply-target {
		font-size: 24rpx;
		color: #666;
	}

	.reply-text {
		font-size: 26rpx;
		color: #333;
		margin-bottom: 4rpx;
		display: block;
	}

	.reply-date {
		font-size: 22rpx;
		color: #999;
	}

	.end-mark {
		text-align: center;
		padding: 30rpx 0;
		color: #999;
		font-size: 24rpx;
	}

	.gift-popup {
		background-color: #fff;
		border-radius: 24rpx 24rpx 0 0;
		padding-bottom: constant(safe-area-inset-bottom);
		/* 兼容 iOS < 11.2 */
		padding-bottom: env(safe-area-inset-bottom);
		position: relative;
		z-index: 999;
	}

	.uni-popup .uni-popup__wrapper {
		padding-bottom: 0 !important;
	}

	.uni-popup-bottom {
		bottom: 0;
	}

	.gift-header {
		padding: 24rpx 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.gift-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.close-btn {
		padding: 10rpx;
	}

	.gift-grid {
		max-height: 400rpx;
		/* 限制最大高度，约两行礼物的高度 */
		overflow-y: auto;
		padding: 20rpx 20rpx 0;
		display: flex;
		flex-wrap: wrap;
		align-content: flex-start;
	}

	.gift-item {
		width: 25%;
		padding: 16rpx;
		box-sizing: border-box;
		display: flex;
		flex-direction: column;
		align-items: center;
		position: relative;
	}

	.gift-item.active {
		background: rgba(255, 36, 66, 0.05);
		border-radius: 12rpx;
	}

	.gift-icon {
		width: 88rpx;
		height: 88rpx;
		margin-bottom: 8rpx;
	}

	.gift-name {
		font-size: 24rpx;
		color: #333;
		margin-bottom: 4rpx;
	}

	.gift-price {
		font-size: 24rpx;
		color: #ff2442;
	}

	.gift-footer {
		padding: 20rpx 30rpx;
		border-top: 1rpx solid #f5f5f5;
	}

	.gift-footer .send-btn {
		height: 88rpx;
		line-height: 88rpx;
		background: linear-gradient(to right, #ff2442, #ff6b6b);
		color: #fff;
		font-size: 32rpx;
		font-weight: 500;
		border-radius: 44rpx;
		text-align: center;
	}

	.gift-footer .send-btn:active {
		opacity: 0.9;
	}

	.skeleton-container {
		padding: 20rpx;
		height: 100vh;
		background-color: #fff;
	}
</style>